package net.zrnecko.bowlingnumbers.session;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import net.zrnecko.bowlingnumbers.entity.User;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

@Name("authenticator")
public class Authenticator {
	@Logger
	Log log;

	@In
	Identity identity;
	@In
	EntityManager entityManager;

	public boolean authenticate() {
		try {
			User user = (User) entityManager
					.createQuery(
							"from User where username = :username and password = :password")
					.setParameter("username", Identity.instance().getUsername())
					.setParameter("password", Identity.instance().getPassword())
					.getSingleResult();

			/*
			 if (user.getRoles() != null)
			 {
			 for (UserRole mr : user.getRoles())
			 Identity.instance().addRole(mr.getName());
			 }
			 */

			log.info("User #{user} successfully logged in");
			return true;
		} catch (NoResultException ex) {
			return false;
		}
	}
}
